package com.booktrade.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.booktrade.dto.CartDTO;
import com.booktrade.entity.Books;
import com.booktrade.entity.Cart;
import com.booktrade.entity.Users;
import com.booktrade.mapper.CartMapper;
import com.booktrade.service.IBooksService;
import com.booktrade.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booktrade.service.IUsersService;
import com.booktrade.vo.CartShopVo;
import com.booktrade.vo.CartVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车表，存储用户购物车中添加的书籍信息 服务实现类
 * </p>
 *
 */
@Service
@RequiredArgsConstructor
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {
    private final IBooksService booksService;
    private final IUsersService usersService;

    @Override
    public void addCart(CartDTO cartDTO, Integer userId) {
        List<Cart> list = this.lambdaQuery().eq(Cart::getUserId, userId).eq(Cart::getBookId, cartDTO.getBookId()).list();
        if(list != null && list.size()>0){
            Cart cart = list.get(0);
            cart.setQuantity(cart.getQuantity()+1);
            this.updateById(cart);
        }else{
            Cart cart = BeanUtil.copyProperties(cartDTO, Cart.class);
            cart.setUserId(userId.intValue());
            this.save(cart);
        }
    }

    @Override
    public void deleteCart(CartDTO cartDTO, Integer userId) {
        List<Cart> list = this.lambdaQuery().eq(Cart::getUserId, userId).eq(Cart::getBookId, cartDTO.getBookId()).list();
        if(list != null && list.size()>0){
            Cart cart = list.get(0);
            if(cart.getQuantity() == 1){
                this.removeById(cart.getId());
            }else{
                cart.setQuantity(cart.getQuantity()-1);
                this.updateById(cart);
            }
        }
    }

    @Override
    public CartShopVo Cartlist(Integer userId) {
        // 查询用户的购物车信息
        List<Cart> cartList = this.list(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId));

        // 将购物车信息转换为视图对象并计算总价
        List<CartVo> cartVoList = cartList.stream().map(cart -> {
            CartVo cartVo = new CartVo();
            cartVo.setBookId(cart.getBookId());
            cartVo.setQuantity(cart.getQuantity());
            // 查询书籍信息
            Books book = booksService.getById(cart.getBookId());
            cartVo.setTitle(book.getTitle());
            cartVo.setPrice(book.getPrice());
            cartVo.setImage(book.getImageUrl());
            cartVo.setSellerId(book.getSellerId());
            Users users = usersService.getById(book.getSellerId());
            cartVo.setSellerName(users.getUsername());

            // 计算该书籍的总价
            BigDecimal totalPrice = book.getPrice().multiply(new BigDecimal(cart.getQuantity()));
            cartVo.setTotalPrice(totalPrice);

            return cartVo;
        }).collect(Collectors.toList());

        // 计算购物车商品总价
        BigDecimal cartTotalPrice = cartVoList.stream()
                .map(CartVo::getTotalPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 添加优惠信息（示例：满 100 减 10 元优惠）
        BigDecimal discount = BigDecimal.ZERO;
        if (cartTotalPrice.compareTo(new BigDecimal("100")) >= 0) {
            discount = new BigDecimal("10");
        }
        CartShopVo cartShopVo = new CartShopVo();
        cartShopVo.setCartVoList(cartVoList);
        cartShopVo.setTotalPrice(cartTotalPrice);
        cartShopVo.setDiscount(discount);
        return cartShopVo;
    }
}
